<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="电表编号" prop="dbbh">
        <el-input v-model="queryParams.dbbh" placeholder="请输入电表编号" clearable style="width: 180px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- 电表实际表号 -->
       <el-form-item label="电表实际表号" prop="energyMeterIp">
        <el-input v-model="queryParams.energyMeterIp" placeholder="请输入电表实际表号" clearable style="width: 180px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="归属载体" prop="zt">
        <el-select v-model="queryParams.zt" placeholder="请选择归属载体" clearable filterable style="width: 150px"
          @focus="fetchCarrierList">
          <el-option v-for="item in carrierList" :key="item.nr" :label="item.nr" :value="item.nr" />
        </el-select>
      </el-form-item>
      <el-form-item label="楼层" prop="lc">
        <el-input v-model="queryParams.lc" placeholder="请输入楼层" clearable style="width: 150px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col> -->
    </el-row>
    <!-- Tab 栏 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabChange">
      <el-tab-pane label="使用中" name="used"></el-tab-pane>
      <el-tab-pane label="空闲" name="free"></el-tab-pane>
    </el-tabs>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="tableData">
      <el-table-column prop="dbbh" label="电表编号" align="center" width="120">
        <template #default="scope">
          <span style=" color:#409eff;cursor:pointer;" @click="openAmmeterDrawer(scope.row)">
            {{ scope.row.dbbh }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="energyMeterIp" label="电表实际表号" align="center" width="120" />
      <el-table-column prop="tid" label="操作码" align="center" width="120" />
      <el-table-column prop="zt" label="归属载体" align="center" />
      <el-table-column prop="lc" label="楼层" width="80" align="center" />
      <el-table-column prop="location" label="所在位置" align="center" width="120" />
      <el-table-column prop="fjh" label="关联房间" align="center">
        <template #default="scope">
          <span :style="scope.row.fjh && activeTab === 'used' ? 'color:#409eff;cursor:pointer;' : ''"
            @click="scope.row.fjh && activeTab === 'used' && handleUpdateRoom(scope.row)">
            {{ scope.row.fjh }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="qymc" label="租户" align="center" width="350" v-if="activeTab === 'used'"
        show-overflow-tooltip>
        <template #default="scope">
          <span :style="scope.row.dbyt === '租用' ? 'color:#409eff;cursor:pointer;' : ''"
            @click="scope.row.dbyt === '租用' && openContactDialog(scope.row, 'invoice')">
            {{ scope.row.qymc }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="lxr" v-if="activeTab === 'used'" label="联系人" align="center">
        <template #default="scope">
          <span style="color: #409eff; cursor: pointer"
            @click="scope.row.dbyt === '租用' && openContactDialog(scope.row, 'contact')">
            {{ scope.row.xm != null ? scope.row.xm : "无" }}
          </span>
        </template>
      </el-table-column>

      <el-table-column prop="dbyt" label="用途" align="center" v-if="activeTab === 'used'" />

      <el-table-column prop="modelName" width="120" label="电表型号" align="center"/>
      <el-table-column prop="magnification" width="80" label="倍率" align="center" />

      <el-table-column prop="dbzt" label="电表状态" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.dbzt === '使用'" type="success">使用</el-tag>
          <el-tag v-else-if="scope.row.dbzt === '空闲'" type="warning">空闲</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button v-if="activeTab === 'free'" link type="primary" @click="handleEnableAssociation(scope.row)">
            启用关联
          </el-button>
          <el-button v-if="activeTab === 'used'" link type="warning" @click="handleWithdraw(scope.row)">
            退用取关
          </el-button>
          <!-- 新增：拉闸/合闸按钮 -->
          <el-button v-if="scope.row.dbSwitch === 1" link type="danger" @click="handleSwitchAmmeter(scope.row, 0)">
            拉闸
          </el-button>
          <el-button v-else-if="scope.row.dbSwitch === 0" link type="success"
            @click="handleSwitchAmmeter(scope.row, 1)">
            合闸
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 新增或编辑电表对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="meterRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="归属载体" prop="nr">
          <el-select v-model="form.nr" placeholder="请选择归属载体" @change="handleCarrierChange">
            <el-option v-for="item in carrierList" :key="item.nra" :label="item.nr" :value="item.nr" />
          </el-select>
        </el-form-item>
        <el-form-item label="楼层" prop="lc">
          <el-input v-model="form.lc" placeholder="请输入楼层" type="number" @input="fetchZlList" />
        </el-form-item>
        <el-form-item label="所在位置" prop="location">
          <el-input v-model="form.location" placeholder="请输入所在位置" />
        </el-form-item>
        <el-form-item label="电表倍率" prop="magnification">
          <el-input v-model="form.magnification" placeholder="请输入电表倍率" type="number" step="0.01" />
        </el-form-item>
        <el-form-item label="电表单价" prop="dbdj">
          <el-input v-model="form.dbdj" placeholder="请输入电表单价" type="number" step="0.01" />
        </el-form-item>
        <el-form-item label="操作地址" prop="tid">
          <el-input v-model="form.tid" placeholder="请输入16进制HEX格式操作地址" />
        </el-form-item>
        <el-form-item label="智联器编号" prop="zlid">
          <el-select v-model="form.zlid" placeholder="请先选择载体与楼层" filterable @focus="fetchZlList" clearable>
            <el-option v-for="item in zlList" :key="item.zlid" :label="item.zlid" :value="item.zlid" />
          </el-select>
        </el-form-item>
        <!-- 电表型号 -->
        <el-form-item label="电表型号" prop="modelId">
          <el-select v-model="form.modelId" placeholder="请选择电表型号" @change="handleMxChange">
            <el-option v-for="item in energyModelList" :key="item.modelId" :label="item.modelName"
              :value="item.modelId" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 启用关联对话框 -->
    <el-dialog :title="'启用关联 - ' + enableForm.dbbh" v-model="enableDialogVisible" width="600px" append-to-body>
      <el-form ref="enableFormRef" :model="enableForm" :rules="enableRules" label-width="120px">
        <el-form-item label="电表用途" prop="yt">
          <el-select v-model="enableForm.yt" placeholder="请选择电表用途" @change="handlePurposeChange">
            <el-option v-for="item in purposeList" :key="item.pxbh" :label="item.nr" :value="item.nr" />
          </el-select>
        </el-form-item>
        <el-form-item label="租户" prop="qymc">
          <template v-if="enableForm.yt === '自用' || enableForm.yt === '公用'">
            <el-input v-model="enableForm.qymc" placeholder="请输入企业名称/区域名称" />
          </template>
          <template v-else-if="enableForm.yt === '租用'">
            <el-select 
              v-model="enableForm.qymc" 
              placeholder="请搜索并选择企业名称" 
              @change="handleEnterpriseChange"
              filterable
              default-first-option
              :reserve-keyword="false"
            >
              <el-option v-for="item in enterpriseListData" :key="item.khbh" :label="item.qymc" :value="item.qymc" />
            </el-select>
          </template>
        </el-form-item>
        <!-- 房源选择仅在非公用时显示 -->
        <el-form-item label="房源选择" prop="fjh" v-if="enableForm.yt !== '公用'">
          <el-select 
            v-model="enableForm.fjh" 
            placeholder="请搜索并选择房源" 
            multiple
            filterable
            default-first-option
            :reserve-keyword="false"
          >
            <el-option v-for="item in roomListData" :key="item.fjh" :label="item.fjh" :value="item.fjh" />
          </el-select>
        </el-form-item>
        <el-form-item label="启用日期" prop="qysj">
          <el-date-picker v-model="enableForm.qysj" type="date" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
            placeholder="请选择启用日期" style="width: 100%" @change="handleEnableDateChange" />
        </el-form-item>
        <el-form-item label="初始电量" prop="csdl">
          <el-input v-model="enableForm.csdl" placeholder="请选择启用日期" type="number" :disabled="true" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelEnableAssociation">取消</el-button>
          <el-button type="primary" @click="submitEnableAssociation">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 关联房间更新对话框 -->
    <el-dialog title="关联房间更新" v-model="updateRoomDialogVisible" width="600px" append-to-body>
      <el-form label-width="100px">
        <el-form-item label="电表编号">
          <el-input v-model="updateRoomForm.dbbh" disabled />
        </el-form-item>
        <el-form-item label="载体位置">
          <el-input v-model="updateRoomForm.zt" disabled />
        </el-form-item>
        <el-form-item label="现关联房间号">
          <el-input v-model="updateRoomForm.fjh" disabled />
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="updateRoomForm.qymc" disabled />
        </el-form-item>
      </el-form>
      <div style="margin-bottom: 10px; font-weight: bold">可选房间列表：</div>
      <el-table :data="roomList" @selection-change="handleRoomSelectionChange" row-key="fjh" ref="roomTableRef" border>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="zt" label="载体" align="center" />
        <el-table-column prop="fjh" label="房间号" align="center" />
        <el-table-column prop="qymc" label="企业名称" align="center" />
      </el-table>
      <template #footer>
        <el-button @click="updateRoomDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpdateRoom">确定</el-button>
      </template>
    </el-dialog>

    <!-- 退用取消关联对话框 -->
    <el-dialog title="退用取消关联" v-model="withdrawDialogVisible" width="500px" append-to-body>
      <el-form :model="withdrawForm" :rules="withdrawRules" ref="withdrawFormRef" label-width="100px">
        <el-form-item label="电表用途">
          <el-input v-model="withdrawForm.dbyt" disabled />
        </el-form-item>
        <el-form-item label="租户">
          <el-input v-model="withdrawForm.qymc" disabled />
        </el-form-item>
        <el-form-item label="房源">
          <el-input v-model="withdrawForm.fjh" disabled />
        </el-form-item>

        <el-form-item label="退用日期" prop="tysj">
          <el-date-picker v-model="withdrawForm.tysj" type="date" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
            placeholder="请选择退用日期" style="width: 100%" @change="handleWithdrawDateChange" />
        </el-form-item>
        <el-form-item label="最终电量" prop="zzdl">
          <el-input v-model="withdrawForm.zzdl" disabled placeholder="请选择退用日期" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="withdrawDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitWithdraw">确定</el-button>
      </template>
    </el-dialog>
    <!-- 关联房间更新对话框 -->
    <el-dialog title="关联房间更新" v-model="updateRoomDialogVisible" width="600px" append-to-body>
      <el-form label-width="100px">
        <el-form-item label="电表编号">
          <el-input v-model="updateRoomForm.dbid" disabled />
        </el-form-item>
        <el-form-item label="载体位置">
          <el-input v-model="updateRoomForm.zt" disabled />
        </el-form-item>
        <el-form-item label="现关联房间号">
          <el-input v-model="updateRoomForm.fjh" disabled />
        </el-form-item>
        <el-form-item label="企业名称">
          <el-input v-model="updateRoomForm.qymc" disabled />
        </el-form-item>
        <el-form-item label="客户编号">
          <el-input v-model="updateRoomForm.khbh" disabled />
        </el-form-item>
      </el-form>
      <div style="margin-bottom: 10px; font-weight: bold">可选房间列表：</div>
      <el-table :data="roomList" @selection-change="handleRoomSelectionChange" row-key="fjh" ref="roomTableRef" border
        :highlight-current-row="true" :max-height="300">
        <el-table-column type="selection" width="55" :selectable="() => true" />
        <el-table-column prop="zt" label="载体" align="center" />
        <el-table-column prop="fjh" label="房间号" align="center" />
        <el-table-column prop="qymc" label="企业名称" align="center" />
      </el-table>
      <template #footer>
        <el-button @click="updateRoomDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpdateRoom">确定</el-button>
      </template>
    </el-dialog>

    <!-- 企业信息弹窗 -->
    <el-dialog :title="contactDialogQymc" v-model="contactDialogVisible" width="1200px" append-to-body>
      <!-- <div style="margin-bottom: 10px; font-weight: bold">
        客户编号：{{ contactDialogKhbh }}
      </div> -->
      <div style="position: absolute; right: 20px; top: 60px;z-index:7">
        <el-button type="primary" @click="openInvoiceEditDialog" style="margin-bottom: 10px">
          补充开票信息
        </el-button>
        <el-button type="primary" @click="openAddContactDialog" style="margin-bottom: 10px; margin-left: 10px">
          添加企业成员
        </el-button>
      </div>
      <el-tabs v-model="contactTab">
        <el-tab-pane label="开票信息" name="invoice">
          <el-descriptions v-if="invoiceInfo" :column="2" border style="margin-bottom: 10px">
            <el-descriptions-item label="租户名称" width="600px">{{
              invoiceInfo.qymc
            }}</el-descriptions-item>

            <el-descriptions-item label="统一信用代码" width="600px"> {{
              invoiceInfo.yyzzh
            }}</el-descriptions-item>
            <el-descriptions-item label="载体项目" width="600px"> {{
              invoiceInfo.zt
            }}</el-descriptions-item>
            <el-descriptions-item label="缴费类型" width="600px">
              <span v-if="invoiceInfo.jflx == 1">后付费</span>
              <span v-else-if="invoiceInfo.jflx == 2">预付费</span>
            </el-descriptions-item>
            <el-descriptions-item label="发票抬头企业名称" width="600px"> {{
              invoiceInfo.kpqymc
            }}</el-descriptions-item>
            <el-descriptions-item label="开票税号" width="600px"> {{
              invoiceInfo.kpsh
            }}</el-descriptions-item>



          </el-descriptions>
          <div v-else style="color: #999; padding: 40px 0; text-align: center">
            暂未补充
          </div>
        </el-tab-pane>
        <!-- 企业成员tab -->
        <el-tab-pane label="企业成员" name="contact">
          <el-table :data="contactList">
            <el-table-column prop="xm" label="姓名" align="center" />
            <el-table-column prop="sj" label="手机号" align="center" width="180" />
            <el-table-column prop="wxh" label="微信号" align="center" />
            <el-table-column prop="zw" label="职务" align="center" />
            <el-table-column prop="qx" label="权限" align="center" />
            <el-table-column prop="sfjf" label="缴费人" align="center">
              <template #default="scope">
                <span :style="scope.row.sfjf === 0 ? 'color:#409eff;cursor:pointer;' : ''">{{ scope.row.sfjf === 0 ? "是"
                  : "否" }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="yx" label="状态" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.yx == 1" type="success">启用</el-tag>
                <el-tag v-else-if="scope.row.yx == 2" type="warning">冻结</el-tag>
                <el-tag v-else-if="scope.row.yx == 0" type="info">已删除</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="180">
              <template #default="scope">
                <el-button link @click="openEditContactDialog(scope.row)">编辑</el-button>
                <el-button v-if="scope.row.yx == 2" link type="primary"
                  @click="handleContactStatus(scope.row, 1)">启用</el-button>
                <el-button v-if="scope.row.yx == 1" link type="warning"
                  @click="handleContactStatus(scope.row, 2)">冻结</el-button>
                <el-button v-if="scope.row.yx != 0" link type="danger"
                  @click="handleContactStatus(scope.row, 0)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 联系人新增/编辑对话框 -->
    <el-dialog :title="contactEditMode ? '编辑联系人' : '新增联系人'" v-model="contactEditDialogVisible" width="900px"
      append-to-body>
      <el-form :model="contactForm" :rules="contactRules" ref="contactFormRef" label-width="80px">
        <el-form-item label="租户">
          <el-input v-model="contactForm.qymc" disabled />
        </el-form-item>
        <el-form-item label="客户编号">
          <el-input v-model="contactForm.khbh" disabled />
        </el-form-item>
        <el-form-item label="电表编号">
          <el-input v-model="contactForm.dbbh" disabled />
        </el-form-item>
        <el-form-item label="姓名" prop="xm">
          <el-input v-model="contactForm.xm" />
        </el-form-item>
        <el-form-item label="手机号" prop="sj">
          <el-input v-model="contactForm.sj" />
        </el-form-item>
        <el-form-item label="微信号" prop="wxh">
          <el-input v-model="contactForm.wxh" />
        </el-form-item>
        <el-form-item label="职务" prop="zw">
          <el-radio-group v-model="contactForm.zw">
            <el-radio label="法人">法人</el-radio>
            <el-radio label="总经理">总经理</el-radio>
            <el-radio label="主办会计">主办会计</el-radio>
            <el-radio label="普通员工">普通员工</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权限" prop="qx">
          <el-radio-group v-model="contactForm.qx">
            <el-radio :label="6">管理员</el-radio>
            <el-radio :label="2">缴费人员</el-radio>
            <el-radio :label="1">查看</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="缴费人" prop="sfjf">
          <el-radio-group v-model="contactForm.sfjf">
            <el-radio :label="0">是</el-radio>
            <el-radio :label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="contactEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitContactForm">确定</el-button>
      </template>
    </el-dialog>
    <!-- 补充开票信息弹窗 -->
    <el-dialog title="补充开票信息" v-model="invoiceEditDialogVisible" width="750px" append-to-body>
      <el-form :model="invoiceForm" ref="invoiceFormRef" label-position="top" label-width="120px">
        <el-form-item label="租户名称" prop="qymc">
          <el-input v-model="invoiceForm.qymc" placeholder="请输入租户名称" disabled />
        </el-form-item>

        <el-form-item label="统一信用代码" prop="yyzzh">
          <el-input v-model="invoiceForm.yyzzh" placeholder="请输入统一信用代码" />
        </el-form-item>
        <el-form-item label="载体项目" prop="zt">
          <el-input v-model="invoiceForm.zt" placeholder="请输入载体项目" />
        </el-form-item>
        <el-form-item label="缴费类型" prop="jflx">
          <el-radio-group v-model="invoiceForm.jflx">
            <el-radio :label="1">后付费</el-radio>
            <el-radio :label="2">预付费</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="发票抬头企业名称" prop="kpqymc">
          <el-input v-model="invoiceForm.kpqymc" placeholder="请输入发票抬头企业名称" />
        </el-form-item>
        <el-form-item label="开票税号" prop="kpsh">
          <el-input v-model="invoiceForm.kpsh" placeholder="请输入开票税号" />
        </el-form-item>

      </el-form>
      <template #footer>
        <el-button @click="invoiceEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitInvoiceForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 详情抽屉 -->
    <el-drawer v-model="amMeterDrawerVisible" title="电表详情" size="50%" direction="rtl" class="custom-drawer">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        <el-descriptions :column="2" border v-if="ammeterInfo">
          <el-descriptions-item label="电表编号">{{ ammeterInfo.dbbh }}</el-descriptions-item>
          <el-descriptions-item label="归属载体">{{ ammeterInfo.zt }}</el-descriptions-item>
          <el-descriptions-item label="楼层">{{ ammeterInfo.lc }}</el-descriptions-item>
          <el-descriptions-item label="所在位置">{{ ammeterInfo.location }}</el-descriptions-item>
          <el-descriptions-item label="电表型号">{{ ammeterInfo.modelName || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="电表倍率">{{ ammeterInfo.magnification || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="最后通讯时间">{{ parseTime(ammeterInfo.timestamp, "{y}-{m}-{d}")
            }}</el-descriptions-item>
          <el-descriptions-item label="总读数">{{ ammeterInfo.totalPower }}</el-descriptions-item>
        </el-descriptions>
        <div v-else style="color: #999; padding: 20px 0;">暂无基本信息</div>
      </el-card>
      <div class="drawer-header"> </div>
      <div class="card-section">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>关联信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border v-if="ammeterInfo">
            <el-descriptions-item label="房间号">{{ ammeterInfo.fjh }}</el-descriptions-item>
            <el-descriptions-item label="企业名称">{{ ammeterInfo.qymc }}</el-descriptions-item>
            <el-descriptions-item label="用途">{{ ammeterInfo.dbyt }}</el-descriptions-item>
            <el-descriptions-item label="智联器编号">{{ ammeterInfo.zlid }}</el-descriptions-item>
          </el-descriptions>
          <div v-else style="color: #999; padding: 20px 0;">暂无关联信息</div>
        </el-card>
      </div>
      <div class="drawer-header"> </div>
      <div class="card-section">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>采集数据</span>
            </div>
          </template>
          <el-descriptions :column="2" border v-if="ammeterInfo">
            <el-descriptions-item label="总电量">{{ formatDecimal(ammeterInfo.totalPower) }}</el-descriptions-item>
            <el-descriptions-item label="a相电压">{{ ammeterInfo.voltageA }}</el-descriptions-item>
            <el-descriptions-item label="b相电压">{{ ammeterInfo.voltageB }}</el-descriptions-item>
            <el-descriptions-item label="c相电压">{{ ammeterInfo.voltageC }}</el-descriptions-item>
            <el-descriptions-item label="a相电流">{{ ammeterInfo.currentA }}</el-descriptions-item>
            <el-descriptions-item label="b相电流">{{ ammeterInfo.currentB }}</el-descriptions-item>
            <el-descriptions-item label="c相电流">{{ ammeterInfo.currentC }}</el-descriptions-item>
            <el-descriptions-item label="a相功率因数">{{ ammeterInfo.powerFactorA }}</el-descriptions-item>
            <el-descriptions-item label="b相功率因数">{{ ammeterInfo.powerFactorB }}</el-descriptions-item>
            <el-descriptions-item label="c相功率因数">{{ ammeterInfo.powerFactorC }}</el-descriptions-item>
            <el-descriptions-item label="a相频率">{{ ammeterInfo.frequencyA }}</el-descriptions-item>
            <el-descriptions-item label="b相频率">{{ ammeterInfo.frequencyB }}</el-descriptions-item>
            <el-descriptions-item label="c相频率">{{ ammeterInfo.frequencyC }}</el-descriptions-item>
            <el-descriptions-item label="无功功率">{{ ammeterInfo.totalReactivePower }}</el-descriptions-item>
          </el-descriptions>
          <div v-else style="color: #999; padding: 20px 0;">暂无采集数据</div>
        </el-card>
      </div>
      <div class="drawer-header"> </div>
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>用电量分析</span>
          </div>
        </template>
        <el-tabs v-model="ammeterDetailTab">
          <!-- 月分日电量 -->
          <el-tab-pane label="月分日电量" name="monthDay">
            <div style="margin-bottom: 10px;">
              <el-date-picker v-model="monthDayFilterMonth" type="month" value-format="YYYY-MM" placeholder="请选择月份"
                style="width: 160px" @change="onMonthDayMonthChange" />
            </div>
            <div style="display: flex; gap: 24px;">
              <div style="flex: 1;">
                <el-card>
                  <div ref="monthDayChartRef" style="height: 350px;"></div>
                </el-card>
              </div>
              <div style="width: 320px;">
                <el-table :data="monthDayList" border height="350" style="margin-top: 10px">
                  <el-table-column prop="day" label="日期" align="center" />
                  <el-table-column prop="used" label="用电量" align="center">
                    <template #default="scope">
                      {{ formatDecimal(scope.row.used) }}
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-tab-pane>
          <!-- 日分时电量 -->
          <el-tab-pane label="日分时电量" name="hour">
            <div style="margin-bottom: 10px;">
              <el-date-picker v-model="hourFilterDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择日期"
                style="width: 160px" @change="onHourDateChange" />
            </div>
            <div style="display: flex; gap: 24px;">
              <div style="flex: 1;">
                <el-card>
                  <div ref="hourChartRef" style="height: 350px;"></div>
                </el-card>
              </div>
              <div style="width: 320px;">
                <el-table :data="hourList" border height="350" style="margin-top: 10px">
                  <el-table-column prop="hour" label="小时" align="center" />
                  <el-table-column prop="used" label="用电量" align="center">
                    <template #default="scope">
                      {{ formatDecimal(scope.row.used) }}
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>


    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, watch } from "vue";
import { parseTime } from "@/utils/ruoyi.js";
const { proxy } = getCurrentInstance();
import * as echarts from "echarts";

// const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
import { deleteContact } from "@/api/carrier/index";

import {
  useList,
  freeList,
  selectzt,
  addMeter,
  enterpriseList,
  startAssociation,
  selectRoom,
  startDayPower,
  withdraw,
  selectContact,
  addContact,
  updateContact,
  selectAmmeter1,
  selectRoom1,
  updateRoom,
  selectAllZl,
  switchAmmeter
} from "@/api/carrier/ammeter";
import { selectzh, addInvoice, selectAmmeterxb } from "@/api/carrier/index";
import { monthDayEnery, hourEnery } from "@/api/energy/index";
import { getMeterList } from "@/api/energy/meter";

import { nextTick } from "vue";

const activeTab = ref("used"); // 当前 Tab
const tableData = ref([]);
const loading = ref(true);
const open = ref(false);
const total = ref(0);
const title = ref("");
const carrierList = ref([]); // 载体列表
const purposeList = ref([]); // 电表用途列表
const enableDialogVisible = ref(false); // 启用关联对话框可见性
const enterpriseListData = ref([]); // 企业列表数据
const roomListData = ref([]); // 房源列表数据
const contactDialogVisible = ref(false); // 联系人列表对话框可见性
const contactEditDialogVisible = ref(false); // 联系人编辑对话框可见性
const contactEditMode = ref(false); // 联系人编辑模式
const contactList = ref([]); // 联系人列表
const contactTab = ref("invoice"); // tabs: contact/企业成员, invoice/开票信息
const updateRoomDialogVisible = ref(false); // 关联房间更新对话框可见性
const roomList = ref([]); // 可选房间列表
const selectedRooms = ref([]);
const zlList = ref([]); // 智联器列表
const energyModelList = ref([]); // 电表型号列表
const withdrawDialogVisible = ref(false); // 退用取消关联对话框可见性
const withdrawForm = reactive({
  dbbh: "",
  qymc: "",
  fjh: "",
  dbyt: "",
  tysj: "",
  zzdl: "",
});
let withdrawRow = null;
// 退用取消关联表单校验规则
const withdrawRules = {
  tysj: [{ required: true, message: "请选择退用日期", trigger: "change" }],
  zzdl: [{ required: true, message: "未获取到最终电量", trigger: "blur" }],
};
const withdrawFormRef = ref(); // 表单ref
const data = reactive({
  form: {
    dbbh: undefined,
    nr: undefined,
    nra: undefined,
    lc: undefined,
    location: undefined,
    magnification: undefined,
    dbdj: undefined, // 新增：电表单价
    tid: undefined,
    zlid: undefined,
    modelId: undefined, // 电表型号
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    dbbh: undefined,
    zt: undefined,
    lc: undefined,
    energyMeterIp: undefined, // 电表IP
  },
  rules: {
    nr: [{ required: true, message: "请选择归属载体", trigger: "change" }],
    lc: [{ required: true, message: "请输入楼层", trigger: "blur" }],
    location: [{ required: true, message: "请输入所在位置", trigger: "blur" }],
    magnification: [
      { required: true, message: "请输入电表倍率", trigger: "blur" },
      {
        pattern: /^\d+(\.\d{1,2})?$/,
        message: "倍率格式不正确，最多两位小数",
        trigger: "blur",
      },
    ],
    tid: [{ required: true, message: "请输入操作地址", trigger: "blur" }],
    dbdj: [
      { required: true, message: "请输入电表单价", trigger: "blur" },
      {
        pattern: /^\d+(\.\d{1,2})?$/,
        message: "单价格式不正确，最多两位小数",
        trigger: "blur",
      },
    ],
    zlid: [{ message: "请选择智联器编号", trigger: "change" }],
  },

});

const { queryParams, rules, form } = toRefs(data);

const enableForm = reactive({
  dbbh: "", // 电表编号
  qymc: "", // 企业名称
  fjh: [], // 房源编号
  yt: "租用", // 电表用途
  qysj: "", // 启用日期
  csdl: 0, // 初始电量
});

const enableRules = {
  qymc: [{ required: true, message: "请选择企业名称", trigger: "change" }],
  fjh: [{ required: true, message: "请选择房源", trigger: "change" }],
  yt: [{ required: true, message: "请选择电表用途", trigger: "change" }],
  qysj: [{ required: true, message: "请选择启用日期", trigger: "change" }],
  csdl: [{ required: true, message: "请选择启用日期", trigger: "blur" }],
};
const enableFormRef = ref(); // 表单ref
// 联系人弹窗相关数据
const contactDialogQymc = ref(""); // 弹窗上方租户
const contactDialogDbbh = ref(""); // 弹窗电表编号
const contactDialogKhbh = ref(""); // 弹窗客户编号

// 联系人表单
const contactForm = reactive({
  qymc: "",
  khbh: "",
  dbbh: "",
  xm: "",
  sj: "",
  wxh: "",
  zw: "",
  qx: "",
  sfjf: 0,
  yhID: undefined, // 编辑时用
});

// 联系人表单校验规则
const contactRules = {
  xm: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  sj: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  qx: [{ required: true, message: "请选择权限", trigger: "change" }],
  sfjf: [{ required: true, message: "请选择是否为缴费人", trigger: "change" }],
};

// 监听权限变化，权限为1时自动设置为非缴费人
watch(
  () => contactForm.qx,
  (val) => {
    if (val === 1) {
      contactForm.sfjf = 1;
    }
  }
);
const contactFormRef = ref(); // 表单ref
// 打开联系人列表弹窗
function openContactDialog(row, type) {
  contactDialogQymc.value = row.qymc;
  contactDialogDbbh.value = row.dbbh;
  contactDialogKhbh.value = row.khbh;
  contactDialogVisible.value = true;
  // 默认tab

  contactTab.value = type;
  fetchContactList();
  fetchInvoiceInfo();
}

// 获取联系人列表
function fetchContactList() {
  selectContact({
    qymc: contactDialogQymc.value,
    dbbh: contactDialogDbbh.value,
    khbh: contactDialogKhbh.value,
  }).then((res) => {
    contactList.value = res.data || [];
  });
}

// 打开编辑联系人弹窗
function openEditContactDialog(row) {
  contactEditMode.value = true;
  Object.assign(contactForm, {
    qymc: contactDialogQymc.value,
    khbh: contactDialogKhbh.value,
    dbbh: contactDialogDbbh.value,
    xm: row.xm,
    sj: row.sj,
    wxh: row.wxh,
    zw: row.zw,
    qx: row.qx,
    sfjf: row.sfjf,
    yhID: row.yhID,
  });
  contactEditDialogVisible.value = true;
  nextTick(() => {
    contactTab.value = "contact";
  });
}

// 提交联系人表单
function submitContactForm() {
  contactFormRef.value.validate((valid) => {
    if (!valid) return;

    if (contactEditMode.value) {
      // 编辑
      updateContact({ ...contactForm, yhID: contactForm.yhID }).then(() => {
        proxy.$modal.msgSuccess("联系人更新成功");
        contactEditDialogVisible.value = false;
        fetchContactList();
      });
    } else {
      // 新增
      addContact({ ...contactForm }).then(() => {
        proxy.$modal.msgSuccess("联系人新增成功");
        contactEditDialogVisible.value = false;
        fetchContactList();
      });
    }
  });
}

/** 查询电表列表 */
function getList() {
  loading.value = true;
  const api = activeTab.value === "used" ? useList : freeList;
  api(queryParams.value).then((response) => {
    if (response.code !== 200) {
      loading.value = false;
      return;
    }
    tableData.value = response.data?.list;
    total.value = response.data?.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    dbbh: undefined,
    zt: undefined,
    lc: undefined,
  };
  getList();
}

/** Tab 切换 */
function handleTabChange(tab, event) {
  console.log(tab, event);
  activeTab.value = tab.props.name;
  queryParams.value.pageNum = 1;
  getList();
}

/** 新增按钮操作 */
function handleAdd() {
  resetForm();
  open.value = true;
  title.value = "新增电表";
  fetchCarrierList();
  fetchPurposeList();
  fetchEnergyModelList();
}

/** 修改按钮操作 */
function handleUpdate(row) {
  resetForm();
  form.value = { ...row };
  open.value = true;
  title.value = "修改电表";
  fetchCarrierList();
  fetchPurposeList();
  fetchEnergyModelList();
}

// /** 删除按钮操作 */
// function handleDelete(row) {
//   deleteMeter(row.dbbh).then(() => {
//     getList();
//   });
// }

/** 提交表单 */
function submitForm() {
  // 新增和编辑都校验
  proxy.$refs.meterRef.validate((valid) => {
    if (!valid) return;
    if (form.value.dbbh) {
      // updateMeter(form).then(() => {
      //   open.value = false;
      //   getList();
      // });
    } else {
      addMeter(form.value).then(() => {
        open.value = false;
        proxy.$modal.msgSuccess("电表新增成功");
        getList();
      });
    }
  });
}

/** 获取载体列表 */
function fetchCarrierList() {
  selectzt({ lxbh: 1, pageNum: 1, pageSize: 10 }).then((response) => {
    carrierList.value = response.data.list || [];
  });
}

/** 获取电表用途列表 */
function fetchPurposeList() {
  selectzt({ lxbh: 2, pageNum: 1, pageSize: 10 }).then((response) => {
    purposeList.value = response.data.list || [];
  });
}

/** 获取电表型号列表 */
function fetchEnergyModelList() {
  getMeterList().then((response) => {
    if (response.code === 200) {
      energyModelList.value = response.rows || [];
    }
  });
}

/** 载体选择时获取 nr 和 nra 并赋值 */
function handleCarrierChange(value) {
  const selectedCarrier = carrierList.value.find((item) => item.nr === value);
  if (selectedCarrier) {
    form.value.nr = selectedCarrier.nr; // 赋值 nr
    form.value.nra = selectedCarrier.nra; // 赋值 nra
    fetchZlList();
  }
}

/** 电表型号选择变化处理 */
function handleMxChange(value) {
  // 可以根据需要在这里添加电表型号选择后的逻辑
  console.log('选择的电表型号ID:', value);
}

/** 重置表单 */
function resetForm() {
  form.value = {
    dbbh: undefined,
    nr: undefined,
    nra: undefined,
    lc: undefined,
    location: undefined,
    magnification: undefined,
    dbdj: undefined,
    tid: undefined,
    zlid: undefined,
    modelId: undefined,
  };
}
// 表单取消
function cancel() {
  resetForm();
  open.value = false;
}

/** 启用关联按钮操作 */
function handleEnableAssociation(row) {
  enableForm.dbbh = row.dbbh; // 设置电表编号
  enableForm.csdl = row.csdl; // 设置初始电量
  enableForm.fjh[0] = row.fjh; // 设置初始电量

  // 获取企业列表
  enterpriseList({ zt: row.zt }).then((response) => {
    enterpriseListData.value = response.data || [];
  });

  // 获取房源列表
  selectRoom({ zt: row.zt, lc: row.lc }).then((response) => {
    roomListData.value = response.data || [];
  });

  // 获取电表用途列表
  fetchPurposeList();

  enableDialogVisible.value = true; // 打开对话框
}

/** 启用日期选择时调用接口获取初始电量 */
function handleEnableDateChange(date) {
  if (!date || !enableForm.dbbh) return;

  startDayPower({ dbbh: enableForm.dbbh, qysj: date }).then((response) => {
    if (response.code === 200 && response.data.length > 0) {
      enableForm.csdl = response.data[0].dbz; // 将返回的电表值赋值给初始电量
    } else {
      enableForm.csdl = 0; // 如果接口未返回数据，设置为默认值
    }
  });
}

/** 电表用途选择时动态调整企业名称输入方式 */
function handlePurposeChange(value) {
  if (value === "自用" || value === "公用") {
    enableForm.qymc = ""; // 清空企业名称
    enableForm.khbh = null; // 设置客户编号为 null
  } else if (value === "租用") {
    enableForm.qymc = ""; // 清空企业名称
    enableForm.khbh = ""; // 清空客户编号
  }
}

/** 企业名称选择时赋值客户编号 */
function handleEnterpriseChange(value) {
  const selectedEnterprise = enterpriseListData.value.find((item) => item.qymc === value);
  if (selectedEnterprise) {
    enableForm.khbh = selectedEnterprise.khbh; // 赋值客户编号
    console.log('选择的企业:', selectedEnterprise.qymc, '客户编号:', selectedEnterprise.khbh);
  }
}

// 提交启用关联
function submitEnableAssociation() {
  enableFormRef.value.validate((valid) => {
    if (!valid) return;
    let fjhValue = "";
    // 公用时不传房间号
    if (enableForm.yt !== "公用") {
      fjhValue = Array.isArray(enableForm.fjh)
        ? enableForm.fjh.join(",")
        : enableForm.fjh;
    }
    startAssociation({
      dbbh: enableForm.dbbh,
      qymc: enableForm.qymc,
      fjh: fjhValue,
      yt: enableForm.yt,
      qysj: enableForm.qysj,
      csdl: enableForm.csdl,
      khbh: enableForm.khbh,
    }).then(() => {
      enableDialogVisible.value = false; // 关闭对话框
      proxy.$modal.msgSuccess("启用关联成功！");
      resetEnableForm(); // 初始化表单
      getList(); // 刷新列表
    });
  });
}

/** 初始化启用关联表单 */
function resetEnableForm() {
  enableForm.dbbh = ""; // 电表编号
  enableForm.qymc = ""; // 企业名称
  enableForm.fjh = []; // 房源编号
  enableForm.yt = "租用"; // 电表用途
  enableForm.qysj = ""; // 启用日期
  enableForm.csdl = 0; // 初始电量
  enableForm.khbh = null; // 客户编号
}

/** 取消启用关联 */
function cancelEnableAssociation() {
  enableDialogVisible.value = false;
  resetEnableForm();
}

/** 退用取消关联按钮操作 */
function handleWithdraw(row) {
  withdrawRow = row;
  withdrawForm.dbbh = row.dbbh;
  withdrawForm.qymc = row.qymc;
  withdrawForm.fjh = row.fjh;
  withdrawForm.dbyt = row.dbyt;
  withdrawForm.tysj = parseTime(new Date(), "{y}-{m}-{d}");
  withdrawForm.zzdl = "";
  withdrawDialogVisible.value = true;
  // 自动获取今天的最终电量
  handleWithdrawDateChange(withdrawForm.tysj);
}

function handleWithdrawDateChange(date) {
  if (!date || !withdrawForm.dbbh) return;
  startDayPower({ dbbh: withdrawForm.dbbh, qysj: date }).then((response) => {
    if (response.code === 200 && response.data.length > 0) {
      withdrawForm.zzdl = response.data[0].dbz;
    } else {
      withdrawForm.zzdl = "";
    }
  });
}

function submitWithdraw() {
  withdrawFormRef.value.validate((valid) => {
    if (!valid) return;
    withdraw({
      dbbh: withdrawForm.dbbh,
      tysj: withdrawForm.tysj,
      zzdl: withdrawForm.zzdl,
    }).then((res) => {
      if (res.code === 200) {
        proxy.$modal.msgSuccess("退用取消关联成功！");
        withdrawDialogVisible.value = false;
        getList();
      } else {
        proxy.$modal.msgError(res.msg || "退用取消关联失败！");
      }
    });
  });
}
// 载体或楼层变动时/下拉聚焦时调用
function fetchZlList() {
  if (!form.value.nr || !form.value.lc) {
    zlList.value = [];
    return;
  }
  selectAllZl({ zt: form.value.nr, lc: form.value.lc }).then((res) => {
    zlList.value = res.data || [];
  });
}

const updateRoomForm = reactive({
  dbid: "",
  zt: "",
  qymc: "",
  khbh: "",
  fjh: "",
});

// 点击“使用中”列表的关联房间时
function handleUpdateRoom(row) {
  // 获取上半区信息
  selectAmmeter1({
    qymc: row.qymc,
    khbh: row.khbh,
    dbid: row.dbid,
  }).then((res) => {
    if (res.code === 200 && res.data) {
      Object.assign(updateRoomForm, {
        dbid: res.data[0].dbid,
        zt: res.data[0].zt,
        qymc: res.data[0].qymc,
        khbh: res.data[0].khbh,
        fjh: res.data[0].fjh,
      });
      // 先获取房间列表，再自动勾选
      selectRoom1({
        qymc: row.qymc,
        khbh: row.khbh,
        dbid: row.dbid,
      }).then((roomRes) => {
        roomList.value = roomRes.data || [];
        // 自动勾选：fjh可能为逗号分隔字符串
        const fjhArr = (updateRoomForm.fjh || "")
          .split(",")
          .map((f) => f.trim())
          .filter((f) => f);

        // 先清空所有勾选
        selectedRooms.value = [];
        nextTick(() => {
          if (proxy.$refs.roomTableRef) {
            proxy.$refs.roomTableRef.clearSelection();
            // 只勾选存在于房间列表的房间号
            roomList.value.forEach((item) => {
              if (fjhArr.includes(item.fjh)) {
                proxy.$refs.roomTableRef.toggleRowSelection(item, true);
                selectedRooms.value.push(item.fjh);
              }
            });
          }
        });
      });
      updateRoomDialogVisible.value = true;
    }
  });
}

// 房间勾选变化
function handleRoomSelectionChange(selection) {
  selectedRooms.value = selection.map((item) => item.fjh);
}

// 提交更新房间
function submitUpdateRoom() {
  if (!selectedRooms.value.length) {
    proxy.$modal.msgWarning("请选择要关联的房间");
    return;
  }
  // 对房间号去重
  const uniqueFjh = Array.from(new Set(selectedRooms.value)).join(",");
  updateRoom({
    dbid: updateRoomForm.dbid,
    fjh: uniqueFjh,
    qymc: updateRoomForm.qymc,
    khbh: updateRoomForm.khbh,
  }).then((res) => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess("关联房间更新成功！");
      updateRoomDialogVisible.value = false;
      getList();
    } else {
      proxy.$modal.msgError(res.msg || "更新失败");
    }
  });
}
const invoiceInfo = ref({});
const invoiceEditDialogVisible = ref(false);
const invoiceForm = reactive({
  qymc: "",
  khbh: "",
  yyzzh: "",
  zt: "",
  jflx: "",
  hkzje: 0,
  yszje: 0,
  wszje: 0,
  kpqymc: "",
  kpsh: "",
  kplx: "",
  kkpje: 0,
  ykpje: 0,
  wkpje: 0,
  qyzt: "",
});
const invoiceFormRef = ref();

function openAddContactDialog() {
  contactEditMode.value = false;
  const isFirst = !contactList.value || contactList.value.length === 0;
  Object.assign(contactForm, {
    qymc: contactDialogQymc.value,
    khbh: contactDialogKhbh.value,
    dbbh: contactDialogDbbh.value,
    xm: "",
    sj: "",
    wxh: "",
    zw: "",
    qx: isFirst ? 6 : "",
    sfjf: 0,
    yhID: undefined,
  });
  contactEditDialogVisible.value = true;
  nextTick(() => {
    contactTab.value = "contact";
  });
}
function fetchInvoiceInfo() {
  invoiceInfo.value = null;
  if (!contactDialogKhbh.value) return;

  selectzh({ khbh: contactDialogKhbh.value })
    .then((res) => {
      if (res.code === 200 && res.data) {
        invoiceInfo.value = res.data;
        console.log("发票信息：", invoiceInfo.value);
      } else {
        invoiceInfo.value = null;
      }
    })
    .catch(() => {
      invoiceInfo.value = null;
    });
}
function openInvoiceEditDialog() {
  // 编辑时带入已有数据
  if (invoiceInfo.value) {
    Object.assign(invoiceForm, invoiceInfo.value);
    console.log(invoiceForm, invoiceInfo.value);
  } else {
    Object.assign(invoiceForm, {
      qymc: contactDialogQymc.value,
      khbh: contactDialogKhbh.value,
      yyzzh: "",
      zt: "",
      jflx: "",
      hkzje: 0,
      yszje: 0,
      wszje: 0,
      kpqymc: contactDialogQymc.value,
      kpsh: "",
      kplx: "",
      kkpje: 0,
      ykpje: 0,
      wkpje: 0,
      qyzt: "",
    });
  }
  invoiceEditDialogVisible.value = true;
}
function submitInvoiceForm() {
  invoiceFormRef.value.validate?.((valid) => {
    if (valid === false) return;
    addInvoice({ ...invoiceForm }).then((res) => {
      if (res.code === 200) {
        proxy.$modal.msgSuccess("补充开票信息成功");
        fetchInvoiceInfo();
      } else {
        proxy.$modal.msgError(res.msg || "补充失败");
      }
    });
  });
}
// 启用/冻结/删除企业成员
function handleContactStatus(row, yx) {
  proxy.$modal.confirm(
    yx === 1
      ? "确定要启用该企业成员吗？"
      : yx === 2
        ? "确定要冻结该企业成员吗？"
        : "确定要删除该企业成员吗？"
  ).then(() => {
    deleteContact({ yx, yhID: row.yhID }).then((res) => {
      if (res.code === 200) {
        proxy.$modal.msgSuccess(
          yx === 1
            ? "启用成功"
            : yx === 2
              ? "冻结成功"
              : "删除成功"
        );
        fetchContactList();
      } else {
        proxy.$modal.msgError(res.msg || "操作失败");
      }
    });
  });
}

const amMeterDrawerVisible = ref(false);
const ammeterInfo = ref(null);
const ammeterDetailTab = ref("monthDay"); // 默认显示月分日电量



function getLastMonthStr() {
  const d = new Date();
  d.setDate(1); // 设置为当月第一天
  d.setMonth(d.getMonth() - 1);

  console.log(parseTime(d, "{y}-{m}"), parseTime(d), d.getMonth());
  return parseTime(d, "{y}-{m}");
}
// 工具函数：获取昨天日期字符串
function getYesterdayStr() {
  const d = new Date();
  d.setDate(d.getDate() - 1);
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  return `${y}-${m}-${day}`;
}
const monthDayList = ref([]); // 月分日电量列表
const hourList = ref([]); // 日分时电量列表 
const monthDayChartRef = ref(); // 月分日电量图表引用
const hourChartRef = ref(); // 日分时电量图表引用
let monthDayChartInstance = null;
let hourChartInstance = null;
// 绘制月分日电量和日分时电量图表

function drawMonthDayChart() {
  if (!monthDayChartRef.value) return;
  if (!monthDayChartInstance) {
    monthDayChartInstance = echarts.init(monthDayChartRef.value);
  }
  const xData = monthDayList.value.map(item => item.day);
  const yData = monthDayList.value.map(item => item.used);
  monthDayChartInstance.setOption({
    tooltip: { trigger: "axis" },
    xAxis: { type: "category", data: xData, name: "日期" },
    yAxis: { type: "value", name: "用电量" },
    series: [
      {
        data: yData,
        type: "line",
        smooth: true,
        name: "用电量"
      }
    ]
  });
  monthDayChartInstance.resize();
}


function drawHourChart() {
  if (!hourChartRef.value) return;
  if (!hourChartInstance) {
    hourChartInstance = echarts.init(hourChartRef.value);
  }
  const xData = hourList.value.map(item => item.hour);
  const yData = hourList.value.map(item => item.used);
  hourChartInstance.setOption({
    tooltip: { trigger: "axis" },
    xAxis: { type: "category", data: xData, name: "小时" },
    yAxis: { type: "value", name: "用电量" },
    series: [
      {
        data: yData,
        type: "line",
        smooth: true,
        name: "用电量"
      }
    ]
  });
  hourChartInstance.resize();
}
// 打开抽屉时初始化筛选时间
function openAmmeterDrawer(row) {
  amMeterDrawerVisible.value = true;
  selectAmmeterxb({ dbbh: row.dbbh }).then(res => {
    if (res.code === 200 && res.data) {
      ammeterInfo.value = { ...res.data['电表详情'], ...res.data['实时数据'] };
      console.log(ammeterInfo.value);
      // 初始化筛选时间
      monthDayFilterMonth.value = getLastMonthStr();
      hourFilterDate.value = getYesterdayStr();
      fetchMonthDayList(row.dbbh, monthDayFilterMonth.value);
      fetchHourList(row.dbbh, hourFilterDate.value);
    } else {
      ammeterInfo.value = null;
      monthDayList.value = [];
      hourList.value = [];
    }
  });
}
const monthDayFilterMonth = ref(getLastMonthStr());
const hourFilterDate = ref(getYesterdayStr());

// 月分日电量筛选
function onMonthDayMonthChange(val) {
  if (ammeterInfo.value && ammeterInfo.value.dbbh) {
    fetchMonthDayList(ammeterInfo.value.dbbh, val);
  }
}
// 日分时电量筛选
function onHourDateChange(val) {
  if (ammeterInfo.value && ammeterInfo.value.dbbh) {
    fetchHourList(ammeterInfo.value.dbbh, val);
  }
}

// 修改fetchMonthDayList和fetchHourList支持传入时间
function fetchMonthDayList(dbbh, month) {
  const m = month || monthDayFilterMonth.value || getLastMonthStr();
  monthDayEnery({ month: m, dbbh }).then(res => {
    monthDayList.value = res.data || [];
    nextTick(drawMonthDayChart);
  });
}
function fetchHourList(dbbh, date) {
  const d = date || hourFilterDate.value || getYesterdayStr();
  hourEnery({ date: d, dbbh }).then(res => {
    hourList.value = res.data || [];
    nextTick(drawHourChart);
  });
}

// 在<script setup>中添加
function handleSwitchAmmeter(row, tNumber) {
  proxy.$modal.confirm(
    tNumber === 0 ? "确定要对该电表执行拉闸操作吗？" : "确定要对该电表执行合闸操作吗？"
  ).then(() => {
    switchAmmeter({ dbbh: row.dbbh, tNumber }).then(res => {
      if (res.code === 200) {
        proxy.$modal.msgSuccess(res.msg || "操作成功！");
        handleQuery();
      } else {
        proxy.$modal.msgError(res.msg || "操作失败！");
      }
    });
  });
}

// 切换tab时自动刷新
watch(ammeterDetailTab, (val) => {
  if (ammeterInfo.value && ammeterInfo.value.dbbh) {
    if (val === "monthDay") {
      fetchMonthDayList(ammeterInfo.value.dbbh, monthDayFilterMonth.value);
    } else if (val === "hour") {
      fetchHourList(ammeterInfo.value.dbbh, hourFilterDate.value);
    }
  }
});

/** 格式化数值为两位小数 */
function formatDecimal(value) {
  if (value === null || value === undefined || value === '') {
    return '';
  }
  return Number(value).toFixed(2);
}

getList();
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #324157;
  font-size: 18px;
  font-weight: bold;
  width: 100%;
  padding: 0 20px;
  height: 30px;
}

.custom-drawer {
  :deep(.el-drawer_Body) {
    background-color: #f4f6f8;
    padding: 20px;
  }

  .drawer-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    color: #324157;
    font-size: 16px;
    font-weight: bold;

    .close-btn {
      background-color: transparent;
      border: none;
      font-size: 16px;
    }
  }

  .box-card {
    margin-top: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    background-color: #ffffff;
    overflow: hidden;
  }

  .card-header {
    font-size: 16px;
    font-weight: bold;
    color: #324157;
  }

  .card-section {
    margin-top: 32px;
  }

  :deep(.el-descriptions__label) {
    background-color: #f9fafb;
    font-weight: normal;
    color: #666;
  }

  :deep(.el-table th) {
    background-color: #f5f7fa;
  }
}
</style>
